package com.tct.worktimeboard.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tct.worktimeboard.config.DataSourceContextHolder;
import com.tct.worktimeboard.config.DataSourceEnum;
import com.tct.worktimeboard.entity.WorkSetting;
import com.tct.worktimeboard.log.DataSource;
import com.tct.worktimeboard.mapper.UserInfoMapper;
import com.tct.worktimeboard.mapper.WorkSettingMapper;
import com.tct.worktimeboard.service.IWorkSettingService;
import com.tct.worktimeboard.util.JsonUtil;
import com.tct.worktimeboard.util.TimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Huhailong
 * @Description
 * @Date 2021/2/23.
 */
@Service
public class WorkSettingServiceImpl extends ServiceImpl<WorkSettingMapper,WorkSetting> implements IWorkSettingService {

    @Resource
    WorkSettingMapper workSettingMapper;
    @Resource
    UserInfoMapper userInfoMapper;

    /**
     * 报工设置
     * @param workSetting 设置信息
     * @return 返回设置状体
     */
    @Override
    public JSONObject addWorkSet(WorkSetting workSetting) {
        workSetting.setCreateTime(TimeUtil.getDateTime());
        int temp = workSettingMapper.selectCount(new QueryWrapper<WorkSetting>().eq("user_id",workSetting.getUserId()));
        if(temp > 0){
            workSettingMapper.update(workSetting,new QueryWrapper<WorkSetting>().eq("user_id",workSetting.getUserId()));
        }else{
            workSettingMapper.insert(workSetting);
        }
        return JsonUtil.toJsonData();
    }

    @Override
    public JSONObject getWorkSet(WorkSetting workSetting) {
        if(workSetting.isPaged()){
            PageHelper.startPage(workSetting.getPageNum(),workSetting.getPageSize());
        }
        QueryWrapper<WorkSetting> queryWrapper = new QueryWrapper<>();
        if(workSetting.getUserId() != null){
            queryWrapper.eq("user_id",workSetting.getUserId());
        }
        DataSourceContextHolder.setContextHolder("db1");
        List<WorkSetting> workSettingPage = workSettingMapper.selectList(queryWrapper);
        DataSourceContextHolder.clear();
        DataSourceContextHolder.setContextHolder("db2");
        workSettingPage.forEach(item->{
            System.out.println("当前数据源"+DataSourceContextHolder.getDataSource());
            item.setUsername(getNameById(item.getUserId()));
        });
        DataSourceContextHolder.clear();
        return JsonUtil.toJsonData(new PageInfo<>(workSettingPage));
    }

    public String getNameById(Long id){
        return userInfoMapper.selectById(id).getName();
    }
}
